<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品详情</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <header>
        <h1>商品详情</h1>
        <nav>
            <a href="index.html">首页</a>
            <a href="product-list.html">商品列表</a>
            <a href="user.html">用户中心</a>
        </nav>
    </header>

    <main>
        <section class="product-detail">
            <div id="product-detail-container">
                <!-- 商品详情将通过JS动态加载 -->
            </div>
            <div class="product-actions">
                <div class="quantity-selector">
                    <label for="quantity">购买数量:</label>
                    <input type="number" id="quantity" value="1" min="1" max="99">
                </div>
                <button id="buy-now-btn" class="btn-primary">立即购买</button>
                <a href="product-list.html" class="btn-secondary">返回商品列表</a>
            </div>
        </section>
    </main>

    <!-- 购买确认弹窗 -->
    <div id="buy-modal" class="modal" style="display: none;">
        <div class="modal-content">
            <h3>确认购买</h3>
            <div id="order-summary"></div>
            <div class="modal-actions">
                <button id="confirm-buy-btn" class="btn-primary">确认购买</button>
                <button id="cancel-buy-btn" class="btn-secondary">取消</button>
            </div>
        </div>
    </div>

    <footer>
        <p>© 2025 电商平台</p>
    </footer>

    <script src="api.js"></script>
    <script>
        let currentProduct = null;

        document.addEventListener('DOMContentLoaded', function() {
            const urlParams = new URLSearchParams(window.location.search);
            const productId = urlParams.get('id');

            if (productId) {
                // 显示加载状态
                document.getElementById('product-detail-container').innerHTML = '<div class="loading">加载商品详情中...</div>';

                // 调用真实API获取商品详情
                getProductDetail(productId).then(result => {
                    if (result.data) {
                        currentProduct = result.data;
                        renderProductDetail(currentProduct);

                        // 立即购买按钮事件
                        document.getElementById('buy-now-btn').addEventListener('click', showBuyModal);

                        // 弹窗事件
                        document.getElementById('confirm-buy-btn').addEventListener('click', confirmPurchase);
                        document.getElementById('cancel-buy-btn').addEventListener('click', hideBuyModal);

                        // 点击弹窗外部关闭
                        document.getElementById('buy-modal').addEventListener('click', function(e) {
                            if (e.target === this) {
                                hideBuyModal();
                            }
                        });
                    } else {
                        throw new Error('商品数据格式错误');
                    }
                }).catch(error => {
                    console.error('获取商品详情失败:', error);
                    handleApiError(error);
                    document.getElementById('product-detail-container').innerHTML =
                        '<p class="error-message">加载商品详情失败，请刷新页面重试</p>';
                });
            } else {
                document.getElementById('product-detail-container').innerHTML =
                    '<p class="error-message">未找到商品信息</p>';
            }
        });

        function renderProductDetail(product) {
            const container = document.getElementById('product-detail-container');
            container.innerHTML = `
                <div class="product-detail-content">
                    <div class="product-image">
                        <div class="product-image-url">
                            <label>商品图片链接:</label>
                            <p class="image-url">${product.productImg}</p>
                        </div>
                    </div>
                    <div class="product-info">
                        <h2>${product.productName}</h2>
                        <p class="price">¥${product.price.toFixed(2)}</p>
                        <div class="product-description">
                            <h4>商品描述</h4>
                            <p>${product.productDesc}</p>
                        </div>
                        <div class="product-features">
                            <h4>商品特点</h4>
                            <ul>
                                <li>✓ 品质保证</li>
                                <li>✓ 全国包邮</li>
                                <li>✓ 7天无理由退换</li>
                                <li>✓ 正品保障</li>
                            </ul>
                        </div>
                    </div>
                </div>
            `;
        }

        function showBuyModal() {
            const quantity = parseInt(document.getElementById('quantity').value);
            if (quantity < 1) {
                alert('购买数量必须大于0');
                return;
            }

            const totalPrice = currentProduct.price * quantity;
            document.getElementById('order-summary').innerHTML = `
                <div class="order-item">
                    <h4>订单摘要</h4>
                    <p>商品: ${currentProduct.productName}</p>
                    <p>单价: ¥${currentProduct.price.toFixed(2)}</p>
                    <p>数量: ${quantity}</p>
                    <p class="total-price">总计: ¥${totalPrice.toFixed(2)}</p>
                </div>
            `;

            document.getElementById('buy-modal').style.display = 'flex';
        }

        function hideBuyModal() {
            document.getElementById('buy-modal').style.display = 'none';
        }

        function confirmPurchase() {
            const quantity = parseInt(document.getElementById('quantity').value);

            // 检查登录状态
            if (!isLoggedIn()) {
                alert('请先登录后再购买');
                window.location.href = 'user.html';
                return;
            }

            hideBuyModal();

            // 调用订单服务的创建订单接口
            createOrder(currentProduct.id, quantity).then(result => {
                if (result.code === 1) {
                    alert(`订单创建成功！\n订单号: ${result.data}`);
                    window.location.href = 'user.html';
                } else {
                    throw new Error(result.msg || '创建订单失败');
                }
            }).catch(error => {
                console.error('创建订单失败:', error);
                handleApiError(error);
            });
        }
    </script>
</body>
</html>